<template>
  <div class="root">
    <div class="top">
      <span>在线诊断</span>
    </div>
    <div class="mid">
      <Card_message_Doc v-for="(item,index) in messages" 
      :key="index" :message="item"/>
    </div>
    <div class="bottom">
      <div class="upload">
        <el-upload
          class="upload-demo"
          drag
          :action="url"
          multiple
          :auto-upload="false"
          style="width: 1600px;"
          :before-upload="handleImages"
          ref="uploadRef"
          @keyup.enter="sendMessage">
          <div class="el-upload__text">
            <div class="img">
              <svg t="1738215268673" class="icon" viewBox="0 0 1024 1024" version="1.1" 
                xmlns="http://www.w3.org/2000/svg" p-id="4420" 
                width="38" height="38"><path d="M833.47 337.03C804.22 187.15 672.62 73.83 511.77 73.83c-160.84 0-292.44 113.32-321.69 263.2C80.42 366.28 0 468.63 0 585.61c0 142.57 113.32 255.9 255.89 255.9h36.56v-73.12h-36.56c-102.35 0-182.78-80.42-182.78-182.78 0-102.35 80.42-182.78 182.78-182.78 0-142.57 113.32-255.89 255.89-255.89s255.9 113.32 255.9 255.89c102.35 0 182.78 80.42 182.78 182.78s-80.42 182.78-182.78 182.78h-36.56v73.12h36.56c142.57 0 255.89-113.33 255.89-255.9-0.01-116.98-80.44-219.33-190.1-248.58z m0 0" fill="#323333" p-id="4421"></path><path d="M544.68 486.91c-14.63-10.97-29.24-14.63-43.87-7.31-3.65 0-7.31 3.65-10.97 7.31L380.17 592.92c-14.62 14.63-14.62 36.56 0 51.18 14.63 14.63 40.21 14.63 54.84 0l43.86-40.21v310.73c0 21.93 18.28 36.55 36.56 36.55 21.93 0 36.55-18.27 36.55-36.55V603.88l43.87 40.21c14.62 14.63 40.21 14.63 54.83 0 14.63-14.62 14.63-36.55 0-51.18l-106-106z m0 0" fill="#323333" p-id="4422"></path></svg>
            </div>
          </div>
        </el-upload>
        <span>点此或拖拽至此上传图片</span>
      </div>
      <div class="input">
        <el-input
          v-model="text"
          style="width: 1800px;font-size: 20px;"
          :autosize="{ minRows: 4, maxRows: 4 }"
          type="textarea"
          placeholder="请输入问题"
          @keyup.enter="sendMessage">
        </el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref,onMounted,onBeforeUnmount} from 'vue'
import Card_message_Doc from '@/components/Card_message_Doc.vue';
import { useRoute } from 'vue-router';
import { useChatStore } from '@/store/message';

const chatStore=useChatStore()
const $route=useRoute()
const url='#'

// 判断是否是JSON消息
const isJSON=(str)=>{
  try{
    JSON.parse(str)
    return true
  }catch(e){
    return false
  }
}

// 存储接收人
let receiver=ref()

let messages=ref([]) //消息列表
let message=ref()//存储单条消息
let text=ref('') //输入的文字
let isFirst=ref(true)//用以标记是否从pinia中获取聊天记录
const did=$route.query.did
let socket = new WebSocket(`ws://47.108.153.130:8090/consultation/false/${did}`);

onMounted(async () => {
  if(isFirst.value){
    messages.value=chatStore.getMessages($route.query.uid)
    console.log(messages.value)
    isFirst.value=false
  }

  socket.onopen = () => {
    console.log('连接成功');
  };

  socket.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  socket.onclose = () => {
    console.log('连接关闭');
  };
  // 监听服务端发送的消息
  socket.onmessage = (event) => {
  console.log('收到消息:', event.data);
    message.value=event.data
    if(isJSON(message.value)){
      message.value=JSON.parse(message.value)
    }
    messages.value.push(message.value);
    receiver.value=message.value.sender||$route.query.uid
  };
  // console.log(JSON.parse(localStorage.getItem('chatStore')))
});

onBeforeUnmount(() => {
  chatStore.saveState()
});


// 发送用户的文字
const uploadRef = ref()
const sendMessage=async (event)=>{
  // 阻止回车键默认打开文件列表的行为
  if (event) {
  // console.log(event)
    event.preventDefault(); // 阻止回车键的默认行为
  }

  if(text.value.trim()){
    const message = {
      value: text.value,
      isUser: true,
      type: 'font'
    };
    const obj={
      receiver:receiver.value||$route.query.uid,
      content:text.value,
      sender:did,
      type:0,
      user:false
    }
    socket.send(JSON.stringify(obj)); // 发送消息到服务器
    // console.log(obj)
    messages.value.push(message)
    text.value=''
  }
  if (uploadRef.value?.uploadFiles?.length > 0) {
    // 手动触发文件处理
    await Promise.all(
      uploadRef.value.uploadFiles.map(file => 
        handleImages(file.raw) // 直接处理原始文件
      )
    );
    uploadRef.value.clearFiles();
  }
}

// 发送图片前的钩子，将图片的Base64编码发送到另一个组件并渲染
const handleImages=async (file) => {
  // 创建FileReader对象
  const reader = new FileReader();
  // 文件读取完毕时触发
  reader.onload = (e) => {
    const imageData = e.target.result; // 获取图片的 Base64 数据
    const message = {
      value: imageData,
      isUser: true,
      type: 'image'
    };
    const obj={
      receiver:receiver.value,
      content:imageData,
      sender:localStorage.getItem('DOCTORID'),
      type:1,
      user:false
    }
    socket.send(JSON.stringify(obj))//发送图片至服务端

    messages.value.push(message);
  };
  reader.readAsDataURL(file); // 异步读取文件内容，读取为Base64编码
  return false
}

</script>

<style lang="scss" scoped>
.root{
  // width: 1920px;
  min-width: 1810px;
  height: auto;
  position: relative;
  .top{
    background-color: #bbb;
    height: 50px;
    // width: 1900px;
    width: 95%;
    padding-left: 10px;
    span{
      font-size: 28px;
      line-height: 50px;
      margin-left: 30px;
    }
  }
  .mid{
    min-height: 600px;
    padding-left: 35px;
    padding-right: 85px;
  }
  .bottom{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    position: absolute;
    width: 1800px;
    min-height: 50px;
    margin-left: 50px;
    // bottom: -140px;
    .input{
      display: flex;
      position: relative;
      width: 60%;
      height: 100%;
      margin-left: -60px;
      .el-button{
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        position: absolute;
        right: 20px;
        bottom: 10px;
        border-radius: 12px;
        height: 40px;width: 70px;
      }
      .el-textarea{
        ::v-deep .el-textarea__inner{
          border-radius: 20px;
        }
      }
    }
    .upload-demo{
      ::v-deep .el-upload-dragger{
        width: 60px;
        height: 70px;
        z-index: 999;
        border-radius: 20px;
        background-color: rgba(0,0,0,0);
        border: none;
        display: flex;
        justify-content: center;
        position: absolute;
        top:95%;
        left:320px
      }
      ::v-deep ul{
        position: absolute;
        z-index: 999;
        top:130%;
        left:15px
      }
      .img{
        margin-top: 20px;
      }
    }
    span{
      position: absolute;
      z-index: 999;
      top:115%;
      left:380px;
      font-size: 18px;
      color: #0984e3;
    }
  }
}
</style>